package com.schedule.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schedule.common.BaseContext;
import com.schedule.common.CustomException;
import com.schedule.common.R;
import com.schedule.dto.EventDto;
import com.schedule.entity.Event;
import com.schedule.mapper.EventMapper;
import com.schedule.service.EventService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class EventServiceImpl extends ServiceImpl<EventMapper, Event> implements EventService {

    @Autowired
    private EventService eventService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据条件删除事件，只根据id、只根据userId,只根据ids
     * @param event
     * @return
     */
    @Override
    public boolean delByCondition(Event event) {
//        String yearMonth = event.getStartTime().getYear()+"-"+event.getStartTime().getMonth();
//        //动态设置key
//        String key="calender_userId_"+event.getUserId()+"_yearMonth_"+yearMonth;
//        redisTemplate.delete(key);
        return eventService.removeById(event.getId());
    }

    /**
     * 根据条件查询用户所有事件
     * 当year、mouth不为空 根据id和年月查询事件
     *
     * @param event
     * @return
     */
    @Override
    public List<Event> listByCondition(EventDto event) {
        if (event.getUserId()==null){
            log.info("获得事件列表中,userId为空");
            throw new CustomException("uerId为空，无法获得事件列表");
        }

        LambdaQueryWrapper<Event> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Event::getUserId,event.getUserId())
               .eq(event.getStartDate()!=null,Event::getStartDate,event.getStartDate());
        List<Event> events = eventService.list(wrapper);
        return events;
    }


    /**
     * 保存事件
     * @param event
     * @return
     */
    @Override
    public R<Event> saveEvent(Event event) {
//        String yearMonth = event.getStartTime().getYear()+"-"+event.getStartTime().getMonth();
//        //动态设置key
//        String key="calender_userId_"+event.getUserId()+"_yearMonth_"+yearMonth;
//        redisTemplate.delete(key);

        if (event.getUserId()==null){
            throw  new CustomException("用户id为空,无法保存事件");
        }
        if (event.getName()==null||event.getName()==""){
            return R.error("事件名为空，无法保存事件");
        }
        log.info("开始新增事件");
        if (event.getStartDate()==null){
            event.setStartDate(LocalDate.now());
        }
        eventService.save(event);

        R<Event> eventR = R.success(event);
        eventR.setMsg("事件保存成功");
        log.info(eventR.toString());
        return eventR;
    }

    /**
     * 事件日历
     * @param eventDto
     * @return
     */
    @Override
    public List<List<Event>> calendar(EventDto eventDto) {
        //日志
        log.info("正在获取用户事件日历");

        //业务异常处理（uerId为空、yaer或month为空）
        if (eventDto.getUserId()==null){
            //log.info("uerId为空,无法获得事件日历");
            throw new CustomException("uerId为空,无法获得事件日历");
        }
        if (StringUtils.isBlank(eventDto.getMonth())||StringUtils.isBlank(eventDto.getYear())){
            //log.info("yaer或month为空,无法获得事件日历");
            throw new CustomException("yaer或month为空,无法获得事件日历");
        }

        //year_date 年-月条件 固定变量
        String year_month=eventDto.getYear().trim()+"-"+eventDto.getMonth().trim();

//        //动态设置key
//        String key="calender_userId_"+eventDto.getUserId()+"_yearMonth_"+year_month;
//
//        //尝试从redis获取缓存
//        List<List<Event>> cacheEventCalender=(List<List<Event>>)redisTemplate.opsForValue().get(key);
//
//        //若缓存不为空 直接返回
//        if (cacheEventCalender!=null){
//            return cacheEventCalender;
//        }

        //条件构造器
        LambdaQueryWrapper<Event> wrapper = new LambdaQueryWrapper<>();



        List<List<Event>> res=new ArrayList<>();

        for (int i = 1; i <=31 ; i++) {

            res.add(new ArrayList<Event>());
            String dayOfMonth="";
            if (i<10){
                dayOfMonth="-0"+i;
            }else {
                dayOfMonth="-"+i;
            }

            wrapper.eq(Event::getUserId,eventDto.getUserId())//匹配用户id
                    .likeRight(Event::getStartDate,year_month)//匹配年-月
                    .likeLeft(Event::getStartDate,dayOfMonth)//匹配dayOfMonth
                    .orderByAsc(Event::getStartTime);//依照getStartTime正序排列


            //加入队列
            res.set(i-1,eventService.list(wrapper));

            //清除sql信息
            wrapper.clear();
        }
//        redisTemplate.opsForValue().set(key,res,60l, TimeUnit.MINUTES);
        return res;
    }


}
